import { NumCardList } from '@/components/NumCardList';
import TimePiceChoice from '@/components/TimePiceChoice';
import { useRequest } from 'ahooks';
import type { DatePickerProps } from 'antd';
import { Button, DatePicker, Form, Modal } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { exoprtApi, getEventStatistics, getPaymentLogsList, PayLogsListType } from './data';
const PaymentLogs: React.FC<any> = () => {
  const [urlSearch] = useSearchParams();
  const [form] = Form.useForm();
  const [exportform] = Form.useForm();
  const [exportModal, setExportModal] = useState<boolean>(false);
  const numCardOptions = [
    {
      label: '全部（元）',
      dataIndex: 'totalAmount',
      key: '0',
    },
    {
      label: '支付宝（元）',
      dataIndex: 'aliPayAmount',
      key: '2',
    },
    {
      label: '微信（元）',
      dataIndex: 'weChatPayAmount',
      key: '1',
    },
  ];
  // 初始化字段定义
  const columns: YmColumnsType<PayLogsListType> = [
    {
      title: '金额（元）',
      dataIndex: 'amount',
      key: 'amount',
      render(value: number) {
        return <div>{(value / 100).toFixed(2)}</div>;
      },
      width: 90,
      ellipsis: true,
    },
    {
      title: '付款时间',
      dataIndex: 'finishPayTime',
      key: 'finishPayTime',
      width: 100,
    },
    {
      title: '付款人',
      dataIndex: 'payPersonName',
      key: 'payPersonName',
      render(value: string, record: any) {
        return (
          <div
            title={value + ' ' + record.payPersonPhone}
            style={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}
          >
            {value} {record.payPersonPhone}
          </div>
        );
      },
      width: 90,
      ellipsis: true,
    },
    {
      title: '所属企业',
      dataIndex: 'entName',
      key: 'entName',
      width: 140,
      ellipsis: true,
    },
    {
      title: '购买简历',
      dataIndex: 'buyInfo',
      key: 'buyInfo',
      width: 140,
      ellipsis: true,
    },
    {
      title: '付款方式',
      dataIndex: 'payType',
      key: 'payType',
      width: 100,
      render(value: number) {
        return <div>{value == 1 ? '微信' : value == 2 ? '支付宝' : '--'}</div>;
      },
    },
    {
      title: '订单号',
      dataIndex: 'thirdOrderNumber',
      key: 'thirdOrderNumber',
      width: 140,
      ellipsis: true,
    },
    {
      title: '付款账户全称',
      dataIndex: 'thirdAccountName',
      key: 'thirdAccountName',
      width: 140,
      ellipsis: true,
    },
  ];

  const payTypeOptions = [
    {
      label: '全部',
      value: '0',
    },
    {
      label: '支付宝',
      value: '2',
    },
    {
      label: '微信',
      value: '1',
    },
  ];
  const [defaultRange] = useState(() => {
    const startTime = urlSearch.get('startTime');
    const endTime = urlSearch.get('endTime');
    if (startTime && endTime) {
      return [dayjs(startTime), dayjs(endTime)] as [dayjs.Dayjs, dayjs.Dayjs];
    }
  });
  const [timeType, setTimeType] = useState<number>(() => {
    if (defaultRange) {
      return -1;
    }
    const days = urlSearch.get('day') ?? 0;
    return Number(days);
  });
  type TimeRangeParams = { startTime?: string; endTime?: string };
  const [params, _search] = useState<TimeRangeParams>(() => {
    let range: typeof defaultRange;
    if (timeType !== 0) {
      range = defaultRange ?? [dayjs().subtract(Number(timeType), 'days'), dayjs()];
    }
    return {
      startTime: range?.[0].format('YYYY-MM-DD'),
      endTime: range?.[1].format('YYYY-MM-DD'),
    };
  });
  const forceUpdate = (p?: any) => {
    _search((s) => ({ ...s, ...p }));
  };
  const { data: staticValues } = useRequest(
    async () => {
      return await getEventStatistics({
        ...params,
      });
    },
    {
      refreshDeps: [params],
    },
  );
  const exportTimeChange: DatePickerProps['onChange'] = (date, dateString) => {
    exportform.setFieldValue('year', dateString.slice(0, 4));
    exportform.setFieldValue('month', dateString.slice(5, 7));
  };
  return (
    <div className="safe_boss_page">
      <div style={{ height: '100%', width: '100%', background: '#fff', padding: '16px' }}>
        <TimePiceChoice
          value={timeType}
          defaultRange={defaultRange}
          onChange={(value, range) => {
            setTimeType(value);
            if (range) {
              forceUpdate({
                startTime: range[0]?.format('YYYY-MM-DD'),
                endTime: range[1]?.format('YYYY-MM-DD'),
              });
            } else {
              forceUpdate({
                startTime: '',
                endTime: '',
              });
            }
          }}
        />
        <NumCardList
          cardMinWidth={120}
          items={numCardOptions}
          onClick={(key) => {
            form.setFieldValue('payType', key);
            forceUpdate();
          }}
          valueRender={(item) => {
            const key = item.dataIndex;
            return staticValues?.[key] ?? '0.00';
          }}
        />
        <YmTable
          wrapperStyle={{ background: '#fff', maxHeight: 'calc(100% - 155px)', minHeight: '314px' }}
          searchForm={{
            formItems: [
              {
                label: '付款方式',
                name: 'payType',
                valueType: {
                  type: 'select',
                  selectProps: {
                    options: payTypeOptions,
                  },
                },
              },
            ],
            form: form,
          }}
          toolBar={{
            prefixNode: (
              <>
                {/* <Button
                  type="primary"
                  onClick={() => {
                    openModal();
                  }}
                >
                  添加事件
                </Button> */}
                <Button
                  type="primary"
                  onClick={() => {
                    // excelRef.current?.openDeatil();
                    setExportModal(true);
                  }}
                >
                  导出
                </Button>
              </>
            ),
          }}
          columns={columns}
          request={async ({ page }, form) => {
            const { current = 1, pageSize = 10 } = page ?? {};
            const response = await getPaymentLogsList({
              pageIndex: current,
              pageSize,
              ...params,
              ...form,
            });
            return response;
          }}
          requestOptions={{
            reFreshDep: [params],
          }}
          rowKey="eventId"
        />
        <Modal
          width={480}
          centered
          style={{ top: '-10vh' }}
          open={exportModal}
          okText="确定"
          title="导出"
          onOk={() => {
            return exportform.validateFields().then((val) => {
              const { year, month } = val;
              exoprtApi({
                year,
                month,
              });
            });
          }}
          onCancel={() => setExportModal(false)}
        >
          <Form
            form={exportform}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 12 }}
            layout="horizontal"
            labelAlign="right"
          >
            <Form.Item name="year" hidden>
              <span></span>
            </Form.Item>
            <Form.Item name="month" hidden>
              <span></span>
            </Form.Item>
            <Form.Item
              label="选择导出月份"
              name="yearMonth"
              rules={[
                {
                  required: true,
                  message: '请选择导出月份',
                },
              ]}
            >
              <DatePicker onChange={exportTimeChange} picker="month" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  );
};
export default PaymentLogs;
